﻿
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Sockets;
//using TouchSocket.Core.Config;
//using TouchSocket.Core.Plugins;
//using TouchSocket.Sockets;
using UnityEngine;
using UnityEngine.UI;

public class RRClient : MonoBehaviour
{
    public static RRClient ins;
    public FHTcpClient fhTcpClient;

    public InputField input_IP;
    public InputField input_Port;


    public GameObject btn_Connect;
    public GameObject btn_DisConnect;


    public List<string> listCmd_HongDengDai = new List<string>();
    public List<string> listCmd_GuoYuanGang = new List<string>();
    public List<string> listCmd_YuZui = new List<string>();
    public List<string> listCmd_ZhongXingChongQing = new List<string>();
    public List<string> listCmd_BBao = new List<string>();
    public List<string> listCmd_ZhongBao = new List<string>();
    public List<string> listCmd_QuanKai = new List<string>();
    public List<string> listCmd_QuanGuan = new List<string>();

    System.Object locker = new System.Object();
    public Action<ITcpClient> Connected;
    private void OnEnable()
    {
        ins = this;
        fhTcpClient = new FHTcpClient();
    }

    void Start()
    {
        //input_IP.text = PlayerPrefs.GetString("IP", "");
        //input_Port.text = PlayerPrefs.GetString("Port", "");

        //if (!string.IsNullOrEmpty(input_IP.text) && !string.IsNullOrEmpty(input_Port.text))
        //{
            Connect();
        //}
    }

    public void Connect()
    {
        string str = File.ReadAllText(Path.Combine(Application.streamingAssetsPath, "host.config"));
        string[] iP_Port = str.Split(':');
        print(iP_Port[0] +"---"+ iP_Port[1]);
        int port1 = 1024;
        int.TryParse(iP_Port[1], out port1);
        fhTcpClient.InitConfig($"{iP_Port[0]}:{port1}");
        fhTcpClient.DisConnected = () =>
        {
            Loom.QueueOnMainThread(() =>
            {
                btn_Connect.SetActive(true);
                btn_DisConnect.SetActive(false);
            });

        };
        fhTcpClient.Connected = (client) =>
        {
            Loom.QueueOnMainThread(() =>
            {
                btn_Connect.SetActive(false);
                btn_DisConnect.SetActive(true);
                //PlayerPrefs.SetString("IP", input_IP.text);   //存储
                //PlayerPrefs.SetString("Port", input_Port.text);   //存储
            });
            if (Connected != null)
            {
                Connected?.Invoke(client);
            }
        };


        Loom.RunAsync(() =>
        {
            lock (locker)
            {
                fhTcpClient.StartConnect();

            }
        });
    }

    private void OnDisable()
    {
        if (fhTcpClient != null)
        {
            fhTcpClient.Close();
        }
    }


    public void OnDisConnect()   //断开连接
    {
        fhTcpClient.Close();
    }

    /// <summary>
    /// 转发对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="dataTypeEnum"></param>
    /// <param name="orderTypeEnum"></param>
    /// <param name="data"></param>
    public void Send<T>(DataTypeEnum dataTypeEnum, OrderTypeEnum orderTypeEnum, T data)
    {
        try
        {
            fhTcpClient.Send(dataTypeEnum, orderTypeEnum, data);
        }
        catch (Exception ex)
        {
            Debug.Log(ex.Message);
        }
    }
    
    /// <summary>
    /// 转发16进制
    /// </summary>
    /// <param name="dataTypeEnum"></param>
    /// <param name="orderTypeEnum"></param>
    /// <param name="hexstr"></param>
    public void SendHex(DataTypeEnum dataTypeEnum, OrderTypeEnum orderTypeEnum, string hexstr)
    {
        fhTcpClient.SendHexStr(dataTypeEnum, orderTypeEnum, hexstr);
    }

    public void SendBytes(DataTypeEnum dataTypeEnum, OrderTypeEnum orderTypeEnum, byte[] bytes)
    {
        fhTcpClient.SendBytes(dataTypeEnum, orderTypeEnum, bytes);
    }

    public void OnSend(string data)
    {
        fhTcpClient.SendASKII(DataTypeEnum.ZK_ShaPan, OrderTypeEnum.Str, data);
    }

    public void SendGBK(string data)
    {
        fhTcpClient.SendGB2312(DataTypeEnum.S_MainHostOld, OrderTypeEnum.Str, data);
    }

    public void SendStr(DataTypeEnum dataTypeEnum, string data)
    {
        fhTcpClient.SendASKII(dataTypeEnum, OrderTypeEnum.Str, data);
    }

    public void SendGBKTwice(string data)
    {
        StartCoroutine(SendTwice(data));
    }
    public void OnSend_HongDengDai()
    {
        StartCoroutine(Test(listCmd_HongDengDai));
    }
    public void OnSend_GuoYuanGang()
    {
        StartCoroutine(Test(listCmd_GuoYuanGang));
    }
    public void OnSend_YuZui()
    {
        StartCoroutine(Test(listCmd_YuZui));
    }
    public void OnSend_ZhongXingChongQing()
    {
        StartCoroutine(Test(listCmd_ZhongXingChongQing));
    }
    public void OnSend_BBao()
    {
        StartCoroutine(Test(listCmd_BBao));
    }
    public void OnSend_ZhongBaoQu()
    {
        StartCoroutine(Test(listCmd_ZhongBao));
    }

    public void OnSend_QuanKai()
    {
        StartCoroutine(Test(listCmd_QuanKai));
    }
    public void OnSend_QuanGuan()
    {
        StartCoroutine(Test(listCmd_QuanGuan));
    }

    IEnumerator Test(List<string> cmds)
    {
        for (int i = 0; i < cmds.Count; i++)
        {
            fhTcpClient.SendASKII(DataTypeEnum.ZK_ShaPan, OrderTypeEnum.Str, cmds[i]);
            yield return new WaitForSeconds(0.1f);
        }
    }

    IEnumerator SendTwice(string data)
    {
        for (int i = 0; i < 2; i++)
        {
            fhTcpClient.SendGB2312(DataTypeEnum.ZK_ShaPan, OrderTypeEnum.Str, data);
            yield return new WaitForSeconds(0.5f);
        }
    }

}
